<?php

class export extends Module {
	var $module_name = "export";
	var $module_version = 0.1;
	var $module_description = "Export of data from YouLoc database in various formats";
	var $export_module = "txt";

	function __construct() {
		parent::__construct();
	}

	function run() {
		try {
			$track_id = 0;
			if ( isset($_GET["export_module"]) ) 	$this->export_module = filter_var($_GET["export_module"],FILTER_SANITIZE_STRING);
			if ( isset($_GET["track_id"]) )	{
				$track_id = filter_var($_GET["track_id"],FILTER_SANITIZE_NUMBER_INT);
			} else {
				Header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error");
				print "Track ID not provided.";
				exit;
			}

			$export_module_filename = sprintf("modules/%s/%.1f/dataformats/%s.php",$this->module_name, $this->module_version, $this->export_module);
	
			if ( file_exists($export_module_filename) ) {
				$data["track"] = $this->get_track_info($track_id);
				$data["coordinates"] = $this->get_track_points($data["track"]["device_id"], $data["track"]["first_id"], $data["track"]["last_id"]);
				include_once($export_module_filename);
			} else {
				Header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error");
				print "Could not appropriate export module.";
				exit;
			}
	
		} catch (Exception $e) {
			Header($_SERVER["SERVER_PROTOCOL"]." 500 Internal Server Error");
			echo 'Caught exception: ',  $e->getMessage(), "\n";
			exit;
	
		}
	}

	function get_track_points ($device_id, $track_first_id, $track_last_id) {
		global $dbh;
		$sql = "SELECT time_received, lat, lon, speed, alt, hdop FROM gps_data WHERE device_id = ? AND id BETWEEN ? AND ? ORDER BY time_received;";
		$stmt = $dbh->prepare($sql);
		$stmt->execute(array($device_id, $track_first_id, $track_last_id));
		$rows = $stmt->fetchAll();
		$data = array();
		$x = 0;
                foreach ($rows as $rs) {
			$data[$x]["lat"] = $rs["lat"];
			$data[$x]["lon"] = $rs["lon"];
			$data[$x]["alt"] = $rs["alt"];
			$data[$x]["speed"] = $rs["speed"];
			$data[$x]["time_received"] = $rs["time_received"];
			$x++;
		}
		return $data;

	}

	function get_track_info ($track_id) {
		global $dbh;
		$sql = "SELECT * FROM tracks WHERE track_id = ?;";
		$stmt = $dbh->prepare($sql);
		$stmt->execute(array($track_id));
		$rs = $stmt->fetch();
		$data = array();
		$data["name"] = $rs["Track"];
		$data["description"] = $rs["start_place"]." - ".$rs["end_place"];
		$data["username"] = $rs["device_id"];
		$data["time"] = $rs["created"];
		$data["first_id"] = $rs["first_id"];
		$data["last_id"] = $rs["last_id"];
		$data["device_id"] = $rs["device_id"];
		return $data;

	}


}

?>
